<script lang="ts" setup>
import { RouteMap, useRouter } from '@/router';
import { onMounted, ref } from 'vue';
import { addIntention, getIntentionConfig } from '@/api/user';
import { useAuthStore } from '@/store/auth';
import { useLocale } from '@/locale/locale';
import { isWechat } from '@/utils/platform';

const { t } = useLocale();
const authStore = useAuthStore();
const router = useRouter();
const languageList = ref([
  {
    name: '简体中文',
    code: 'zh'
  },
  {
    name: 'English',
    code: 'en'
  },
  {
    name: '日本語',
    code: 'ja'
  },
  {
    name: '한국어',
    code: 'ko'
  },
  {
    name: '繁体中文',
    code: 'zh_CN'
  }
]);
const info = ref({
  linkPhone: '',
  wechatNo: '',
  wechatCodeImg: '',
  lineId: '',
  lineImg: ''
});
const wechatNoPopupRef = ref();
const linePopupRef = ref();
const languageIndex = ref(-1);
const formVal = ref({
  country: {
    name: authStore.loginForm.countryName ? authStore.loginForm.countryName : '',
    code: authStore.loginForm.countryPrefix ? authStore.loginForm.countryPrefix : ''
  },
  language: '',
  phoneArea: authStore.loginForm.countryPrefix ? authStore.loginForm.countryPrefix : '',
  phone: '',
  wechatNo: '',
  lineId: '',
  email: '',
  remark: ''
});

async function getInfo() {
  const res = await getIntentionConfig();
  if (res.code == 0) {
    info.value = res.data;
  }
}

function makePhone() {
  if (!info.value.linkPhone) {
    return;
  }
  uni.makePhoneCall({
    phoneNumber: info.value.linkPhone
  });
}

function openWechatNoPopup() {
  wechatNoPopupRef.value.open();
}

function openLinePopup() {
  linePopupRef.value.open();
}

function setLanguage(e: any) {
  languageIndex.value = e.detail.value;
  formVal.value.language = languageList.value[e.detail.value].name;
}

function saveImg(img: string) {
  if (!img) {
    uni.showToast({
      title: t('LCKey_saveImgFail'),
      icon: 'none'
    });
    return false;
  }

  uni.showLoading({ title: '', mask: true });
  uni.authorize({
    scope: 'scope.writePhotosAlbum',
    success() {
      // 先下载图片
      uni.downloadFile({
        url: img, // 网络图片的 URL
        success: (downloadRes) => {
          if (downloadRes.statusCode === 200) {
            // 下载成功，保存图片到相册
            uni.saveImageToPhotosAlbum({
              filePath: downloadRes.tempFilePath, // 下载后的临时文件路径
              success: function () {
                uni.hideLoading();
                uni.showToast({
                  title: t('LCKey_saveImgSuss'),
                  icon: 'none'
                });
              },
              fail: function (err) {
                uni.hideLoading();
                console.error(err);
                uni.showToast({
                  title: t('LCKey_saveImgFail'),
                  icon: 'none'
                });
              }
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: t('LCKey_saveImgFail'),
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            title: t('LCKey_saveImgFail'),
            icon: 'none'
          });
          console.error(err);
        }
      });
    },
    fail: function (err) {
      uni.hideLoading();
      console.error(err);
    }
  });
}

const changeCountry = (name: string, code: string) => {
  formVal.value.country.name = name;
  formVal.value.country.code = code;
};

const changePhoneArea = (e: string) => {
  formVal.value.phoneArea = e;
};

defineExpose({
  changeCountry,
  changePhoneArea
});

async function toSubmit() {
  if (!formVal.value.country.code) {
    uni.showToast({
      title: t('LCKey_country'),
      icon: 'none'
    });
    return;
  }
  if (!formVal.value.language) {
    uni.showToast({
      title: t('LCKey_yourSelectLanguage'),
      icon: 'none'
    });
    return;
  }
  if (!formVal.value.phone) {
    uni.showToast({
      title: t('LCKey_mobileInputPlaceholder'),
      icon: 'none'
    });
    return;
  }
  if (!formVal.value.email) {
    uni.showToast({
      title: t('LCKey_YourInputEmail'),
      icon: 'none'
    });
    return;
  }

  const payload: any = {
    country: formVal.value.country.name,
    phone: formVal.value.phone,
    phoneArea: formVal.value.phoneArea,
    language: formVal.value.language,
    mail: formVal.value.email,
    remark: formVal.value.remark,
    wechatNo: formVal.value.wechatNo,
    lineId: formVal.value.lineId
  };
  const res = await addIntention(payload);
  if (res.code == 0) {
    uni.showToast({
      title: t('LCKey_SubmittedsuccessfullyMsg'),
      icon: 'none'
    });
    router.back();
  }
}

onMounted(async () => {
  await getInfo();
});
</script>

<template>
  <uni-nav-bar
    v-if="isWechat()"
    :border="false"
    :title="t('LKey_projectConsulting')"
    fixed
    left-icon="left"
    status-bar
    @click-left="router.back"
  />
  <view class="intention-index-contain">
    <view class="intention-index-contain-top">
      <view class="intention-index-contain-top-title">{{ t('LCKey_WelcomeConsultation') }}</view>
      <view class="intention-index-contain-top-tips">{{ t('LCKey_ProfessionalConsultants') }}</view>
      <view class="intention-index-contain-top-item">
        <view @click="makePhone">
          <image mode="widthFix" src="/static/intention/phone.png" />
          <text>{{ t('LCKey_ByPhone') }}</text>
        </view>
        <view @click="openWechatNoPopup">
          <image mode="widthFix" src="/static/intention/wechat.png" />
          <text>{{ t('LCKey_WeChat') }}</text>
        </view>
        <view @click="openLinePopup">
          <image mode="widthFix" src="/static/intention/line.png" />
          <text>{{ t('LCKey_LINE') }}</text>
        </view>
      </view>
    </view>

    <view class="intention-index-contain-info">
      <view class="intention-index-contain-info-input">
        <view
          class="intention-index-contain-info-input-item"
          @click="
            router.to(RouteMap.countries, {
              type: 'intentionCountry',
              code: formVal.country.code
            })
          "
        >
          <view class="intention-index-contain-info-input-item-title">
            {{ t('LCKey_country') }}
            <text>*</text>
          </view>
          <view class="intention-index-contain-info-input-item-input">
            <view
              :class="!formVal.country.code ? 'placeholder' : ''"
              class="intention-index-contain-info-input-item-input-country"
            >
              {{ formVal.country.code ? formVal.country.name : t('LCKey_country') }}
            </view>
            <image mode="widthFix" src="/static/intention/icon_arrow_right.png" />
          </view>
        </view>
        <view class="intention-index-contain-info-input-item">
          <view class="intention-index-contain-info-input-item-title">
            {{ t('LCKey_yourLanguage') }}
            <text>*</text>
          </view>
          <view class="intention-index-contain-info-input-item-input">
            <picker
              :range="languageList"
              :value="languageIndex < 0 ? 0 : languageIndex"
              range-key="name"
              style="width: 100%"
              @change="setLanguage"
            >
              <view class="intention-index-contain-info-input-item-input-value">
                <view :class="languageIndex < 0 ? 'placeholder' : ''">
                  {{
                    languageIndex >= 0
                      ? languageList[languageIndex].name
                      : t('LCKey_yourSelectLanguage')
                  }}
                </view>
                <image mode="widthFix" src="/static/intention/icon_arrow_right.png" />
              </view>
            </picker>
          </view>
        </view>
        <view class="intention-index-contain-info-input-item">
          <view class="intention-index-contain-info-input-item-title">
            {{ t('LCKey_mobile') }}
            <text>*</text>
          </view>
          <view class="intention-index-contain-info-input-item-input">
            <view class="intention-index-contain-info-input-item-input-phone">
              <view
                @click="
                  router.to(RouteMap.countries, {
                    type: 'intentionPhoneArea',
                    code: formVal.phoneArea
                  })
                "
              >
                {{ formVal.phoneArea }}
                <image mode="widthFix" src="/static/intention/icon_arrow_down.png" />
              </view>
              <input
                v-model="formVal.phone"
                :placeholder="t('LCKey_mobileInputPlaceholder')"
                placeholder-class="placeholder"
                readonly
                type="tel"
              />
            </view>
          </view>
        </view>
        <view class="intention-index-contain-info-input-item">
          <view class="intention-index-contain-info-input-item-title">
            {{ t('LCKey_YourWeChatID') }}
          </view>
          <view class="intention-index-contain-info-input-item-input">
            <input
              v-model="formVal.wechatNo"
              :placeholder="t('LCKey_FillInYourWeChatID')"
              placeholder-class="placeholder"
              readonly
              type="text"
            />
          </view>
        </view>
        <view class="intention-index-contain-info-input-item">
          <view class="intention-index-contain-info-input-item-title">
            {{ t('LCKey_YourLineID') }}
          </view>
          <view class="intention-index-contain-info-input-item-input">
            <input
              v-model="formVal.lineId"
              :placeholder="t('LCKey_FillInYourLineID')"
              placeholder-class="placeholder"
              readonly
              type="text"
            />
          </view>
        </view>
        <view class="intention-index-contain-info-input-item">
          <view class="intention-index-contain-info-input-item-title">
            {{ t('LCKey_YourEmail') }}
            <text>*</text>
          </view>
          <view class="intention-index-contain-info-input-item-tips">
            {{ t('LCKey_YourEmailInfo') }}
          </view>
          <view class="intention-index-contain-info-input-item-input">
            <input
              v-model="formVal.email"
              :placeholder="t('LCKey_YourInputEmail')"
              placeholder-class="placeholder"
              readonly
              type="email"
            />
          </view>
        </view>
        <view class="intention-index-contain-info-input-item">
          <view class="intention-index-contain-info-input-item-title">
            {{ t('LCKey_YourMessageRemarks') }}
          </view>
          <view class="intention-index-contain-info-input-item-input">
            <input
              v-model="formVal.remark"
              :placeholder="t('LCKey_Yourmessage')"
              placeholder-class="placeholder"
              readonly
              type="text"
            />
          </view>
        </view>
      </view>
    </view>

    <view class="intention-index-contain-bottom">
      <view class="intention-index-contain-bottom-info">
        {{ t('LCKey_ClickingSubmitMsg').split(/@Agreement和|@Privacy/)[0] }}
        <text @click="router.to(RouteMap.webWeb, { key: 'useragreement' })">
          {{ t('LLKey_userAgreement') }}
        </text>
        {{ t('LCKey_ClickingSubmitMsg').split(/@Agreement和|@Privacy/)[1] }}
        <text
          @click="
            router.to(RouteMap.webWebview, { url: encodeURIComponent(authStore.GetprivacyText()) })
          "
        >
          {{ t('LLKey_privacyPolicy') }}
        </text>
        {{ t('LCKey_ClickingSubmitMsg').split(/@Agreement和|@Privacy/)[2] }}
      </view>
      <view class="intention-index-contain-bottom-btn" @click="toSubmit">
        {{ t('LCKey_SubmitNow') }}
      </view>
    </view>
  </view>

  <apt-popup ref="wechatNoPopupRef" :showConfirmBtn="false" :title="t('LCKey_WeChat')">
    <view class="apt-wechat-no-contain">
      <view v-if="info.wechatCodeImg" class="apt-wechat-no-contain-img">
        <image :src="info.wechatCodeImg" mode="widthFix" />
      </view>
      <view class="apt-wechat-no-contain-no">{{ t('LCKey_WeChatID') }}：{{ info.wechatNo }}</view>
      <view class="apt-wechat-no-contain-btn">
        <view @click="saveImg(info.wechatCodeImg)">{{ t('LCKey_SaveQrCode') }}</view>
      </view>
    </view>
  </apt-popup>

  <apt-popup ref="linePopupRef" :showConfirmBtn="false" :title="t('LCKey_LINE')">
    <view class="apt-wechat-no-contain">
      <view v-if="info.lineImg" class="apt-wechat-no-contain-img">
        <image :src="info.lineImg" mode="widthFix" />
      </view>
      <view class="apt-wechat-no-contain-no">LIND ID：{{ info.lineId }}</view>
      <view class="apt-wechat-no-contain-btn">
        <view @click="saveImg(info.lineImg)">{{ t('LCKey_SaveQrCode') }}</view>
      </view>
    </view>
  </apt-popup>
</template>

<style lang="scss" scoped>
.intention-index-contain {
  &-top {
    background: #ffffff;
    border-bottom-left-radius: 20rpx;
    border-bottom-right-radius: 20rpx;
    padding: 28rpx 32rpx 34rpx;

    &-title {
      color: #3d3d3d;
      font-size: 44rpx;
      font-weight: 500;
      line-height: 62rpx;
    }

    &-tips {
      color: #3d3d3d;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 40rpx;
      margin-top: 8rpx;
    }

    &-item {
      display: flex;
      justify-content: space-between;
      margin-top: 32rpx;

      view {
        align-items: center;
        background: rgba(38, 156, 116, 0.06);
        border: 1rpx solid #269c74;
        border-radius: 4rpx;
        display: flex;
        height: 76rpx;
        justify-content: center;
        padding: 0 26rpx;

        image {
          display: block;
          width: 32rpx;
        }

        text {
          color: #269c74;
          font-size: 28rpx;
          font-weight: 500;
          line-height: 40rpx;
          margin-left: 8rpx;
        }
      }
    }
  }

  &-info {
    background: #ffffff;
    border-radius: 20rpx;
    margin-top: 20rpx;
    padding: 40rpx 32rpx;

    &-tips {
      color: #3d3d3d;
      font-size: 24rpx;
      font-weight: 400;
      line-height: 34rpx;
    }

    &-input {
      margin-top: 30rpx;

      &-item {
        border-bottom: 1px solid #f4f4f4;
        padding-top: 32rpx;

        &:last-child {
          border-bottom: none;
        }

        &-title {
          color: #3d3d3d;
          font-size: 28rpx;
          font-weight: 500;
          line-height: 40rpx;

          text {
            color: #d13820;
          }
        }

        &-tips {
          color: #df7c32;
          font-size: 24rpx;
          font-weight: 400;
          line-height: 34rpx;
          margin-top: 8rpx;
        }

        &-input {
          align-items: center;
          display: flex;
          justify-content: space-between;
          padding: 20rpx 0;

          &-country {
            color: #3d3d3d;
            font-size: 28rpx;
            font-weight: 400;
            line-height: 40rpx;

            &.placeholder {
              color: #adaeb0;
            }
          }

          input {
            color: #3d3d3d;
            flex: 1;
            font-size: 28rpx;
            font-weight: 400;
            height: 40rpx;
            line-height: 40rpx;

            &.placeholder {
              color: #adaeb0;
            }
          }

          image {
            display: block;
            width: 32rpx;
          }

          &-value {
            align-items: center;
            display: flex;
            justify-content: space-between;

            view {
              color: #3d3d3d;
              font-size: 28rpx;
              font-weight: 400;
              line-height: 40rpx;

              &.placeholder {
                color: #adaeb0;
              }
            }

            image {
              display: block;
              width: 32rpx;
            }
          }

          &-phone {
            align-items: center;
            display: flex;
            flex: 1;

            view {
              align-items: center;
              color: #3d3d3d;
              display: flex;
              font-size: 28rpx;
              font-weight: 400;
              line-height: 40rpx;

              image {
                display: block;
                margin-left: 8rpx;
                margin-right: 20rpx;
                width: 32rpx;
              }
            }
          }
        }
      }
    }
  }

  &-bottom {
    padding: 24rpx 32rpx 60rpx;
    padding-bottom: 60rpx;
    padding-bottom: calc(constant(safe-area-inset-bottom) + 60rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 60rpx);

    &-info {
      color: #979797;
      font-size: 24rpx;
      font-weight: 400;
      line-height: 40rpx;

      text {
        color: #3269fb;
      }
    }

    &-btn {
      background: #269c74;
      border-radius: 76rpx;
      color: #ffffff;
      font-size: 30rpx;
      font-weight: 500;
      height: 76rpx;
      line-height: 76rpx;
      margin-top: 36rpx;
      text-align: center;
    }
  }
}

.apt-wechat-no-contain {
  &-img {
    padding: 72rpx 0 24rpx;

    image {
      display: block;
      margin: 0 auto;
      width: 418rpx;
    }
  }

  &-no {
    color: #3d3d3d;
    font-size: 32rpx;
    font-weight: 500;
    line-height: 44rpx;
    text-align: center;
  }

  &-btn {
    display: flex;
    justify-content: center;
    margin-top: 20rpx;

    view {
      background: rgba(223, 124, 50, 0.1);
      border: 1rpx solid #df7c32;
      border-radius: 12rpx;
      color: #df7c32;
      font-size: 28rpx;
      font-weight: 400;
      height: 72rpx;
      line-height: 72rpx;
      padding: 0 14rpx;
    }
  }
}
</style>
